package com.moon.interview.sentinel;

import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moon.interview.common.BaseResponse;
import com.moon.interview.common.ResultUtils;
import com.moon.interview.exception.SysErrorCode;
import jakarta.servlet.http.HttpServletRequest;

public class SentinelGlobalHandler {
    /**
     * 限流操作
     * 熔断：执行降级操作
     *
     * @param type api 单个接口限流； ip IP限流
     */
    public static BaseResponse<Page> handleBlockException(HttpServletRequest request, BlockException ex, String type) {
        // 业务异常
        if (!BlockException.isBlockException(ex)) {
            Tracer.trace(ex);
            return ResultUtils.error(SysErrorCode.SYSTEM_ERROR, "系统错误");
        }
        // 降级操作
        if (ex instanceof DegradeException) {
            return handleFallback(request, ex);
        }
        // 限流操作
        String message = BlockMessageEnums.getMessageByType(type);
        return ResultUtils.error(SysErrorCode.SYSTEM_ERROR, message);
    }

    /**
     * 降级操作：直接返回空数据或本地数据
     */
    public static BaseResponse<Page> handleFallback(HttpServletRequest request, Throwable ex) {
        // 可以返回本地数据或空数据
        return ResultUtils.success(null);
    }
}
